# -*- coding: utf-8 -*-

"""
@Datetime: 2018/11/6
@Author: Zhang Yafei
"""
import pika
import uuid


class CmdRpcClient(object):
    def __init__(self):
        credentials = pika.PlainCredentials('admin', 'admin')
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(
            '192.168.137.3', 5672, '/', credentials))
        self.channel = self.connection.channel()

        result = self.channel.queue_declare(exclusive=True)
        self.callback_queue = result.method.queue

        self.channel.basic_consume(self.on_response, no_ack=True,
                                   queue=self.callback_queue)   #准备接受命令结果

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

    def call(self, n):
        self.response = None
        self.corr_id = str(uuid.uuid4())  #唯一标识符
        self.channel.basic_publish(exchange='',
                                   routing_key='rpc_queue',
                                   properties=pika.BasicProperties(
                                       reply_to=self.callback_queue,
                                       correlation_id=self.corr_id,
                                   ),
                                   body=n)
        while self.response is None:
            self.connection.process_data_events()   #检查队列里有没有新消息，但不会阻塞
        return self.response


fibonacci_rpc = CmdRpcClient()

while True:
    cmd = input('>>:')
    if cmd != 'exit':
        response = fibonacci_rpc.call(cmd)
        # print(response.decode('gbk'))
        print(response.decode())
    else:
        break
exit('ubuntu process finished...')